﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace PdfConvert
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            if (!CheckInstall.IsDotNetRuntimeInstalled())
            {
                string installerPath = Path.Combine(
                        AppDomain.CurrentDomain.BaseDirectory,                     
                        "windowsdesktop-runtime-6.0.36-win-x64.exe"
                    );

                if (File.Exists(installerPath))
                    {
                        var result = MessageBox.Show(
                        "需要安装.NET 6运行时。是否立即安装？",
                        "依赖缺失",
                        MessageBoxButton.YesNo
                    );

                    if (result == MessageBoxResult.Yes)
                    {
                        // 以管理员权限静默安装运行时
                        bool installSuccess = RunInstallerWithAdmin(installerPath);

                        if (installSuccess)
                        {
                            MessageBox.Show("安装完成，请重新启动应用程序。");
                        }
                        else
                        {
                            MessageBox.Show("安装失败，请手动安装运行时！");
                        }

                        // 关闭当前应用
                        Current.Shutdown();
                        return;
                    }
                    else
                    {
                        Current.Shutdown();
                    }
                }
                else
                {
                    MessageBox.Show("运行时安装程序未找到，请联系管理员。");
                    Current.Shutdown();
                    return;
                }
            }
        }


        // 以管理员权限运行安装程序
        private bool RunInstallerWithAdmin(string installerPath)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = installerPath,
                    Arguments = "/passive /norestart", // 静默安装参数
                    Verb = "runas", // 请求管理员权限
                    UseShellExecute = true
                };

                Process process = Process.Start(startInfo);
                process.WaitForExit(); // 等待安装完成
                return process.ExitCode == 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"安装失败: {ex.Message}");
                return false;
            }
        }
    }
}
